package org.example.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.example.entity.VacationBalance;
import org.example.models.R;
import org.example.service.VacationBalanceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.Date;

@RestController
@RequestMapping("/vacationBalance")
public class VacationBalanceController {

    @Autowired
    private VacationBalanceService vacationBalanceService;

    @GetMapping("/list")
    public R<VacationBalance> list(@RequestAttribute("userId") Integer userId) {
        QueryWrapper<VacationBalance> queryWrapper = new QueryWrapper<>();

        queryWrapper.eq("user_id", userId);

        return R.success(vacationBalanceService.getOne(queryWrapper));
    }

    @PostMapping("/update")
    public R<String> update(@RequestParam("totalLeaveDays") BigDecimal totalLeaveDays, @RequestAttribute("userId") Integer userId) {
        QueryWrapper<VacationBalance> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);

        VacationBalance vacationBalance = vacationBalanceService.getOne(queryWrapper);

        vacationBalance.setVacationDays(vacationBalance.getVacationDays().subtract(totalLeaveDays));
        vacationBalance.setUpdatedAt(new Date());

        return vacationBalanceService.updateById(vacationBalance) ? R.success("更新成功") : R.error("更新失败");
    }

}
